<template>
    <div style="height: 45px;box-shadow:0px 5px 20px 0px rgba(0,0,0,0.1);padding: 0 10px">
        <div style="float: left;font-size: 25px;line-height: 45px">欢迎使用尤八哥客服系统</div>
        <div style="float: right;line-height: 45px;">
            <el-avatar  style="height:35px;width: 35px;margin: 5px" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            <div style="float: right;line-height:45px;">{{nickName}}</div>
        </div>
    </div>
    <el-row style="width: 100vw;">
        <el-col :span="24">
            <div style="padding: 10px">
                <!--消息框-->
                <div class ="scrollDiv" @click="" ref="msgArea" style="height:calc(100vh - 260px); overflow:auto; border: 1px solid #ccc;
                border-radius: 5px;background-color: #f5f5f5">
                    <div v-for="(msg, idx) in chat.msgs">
                        <!--//显示坐席的消息-->
                        <div v-if="msg.sender == 'agent'" class="el-row" style="padding: 5px 0">
                            <div class="el-col el-col-2" style="text-align: right">
                              <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                                <img src="@/assets/agent-icon.png" style="object-fit: cover;">
                              </span>
                            </div>
                            <div class="el-col el-col-22" style="text-align: left; padding-left: 10px ">
                                <div class="tip left">{{msg.content}}</div>
                                <div class="time">{{moment(msg.createTime).format("yyyy-MM-DD HH:mm:ss")}}</div>
                            </div>
                        </div>
                        <!--显示客户的消息-->
                        <div v-if="msg.sender == 'client'" class="el-row" style="padding: 5px 0">
                            <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
                                <div class="time">{{moment(msg.createTime).format("yyyy-MM-DD HH:mm:ss")}}</div>
                                <div class="tip right">{{msg.content}}</div>
                            </div>
                            <div class="el-col el-col-2">
                             <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                                <img src="@/assets/client-icon.png" style="object-fit: cover;">
                             </span>
                            </div>
                        </div>
                    </div>
                </div>
                <!--消息框结束-->
                <div style="width:100%;height:20px;border:none;">
                </div><!--输入框结束-->
                <!--输入框-->
                <div v-if="chat.alive" style="height: 120px;border-radius: 5px;border:1px solid #ccc;">
                    <textarea @keydown.enter.prevent="send(chat)" style="height: 100%; width: 100%; padding-top: 10px;
                     outline: none;border: none; resize: none" v-model="chat.inputBox" />
                </div><!--输入框结束-->
                <el-button style="margin-top:10px;float:right" v-if="chat.alive" type="primary"  @click="send(chat)">发送</el-button>
            </div>
        </el-col>
    </el-row>
    <ClientLogin ref="clientLogin" @afterLogin="logined"/>
</template>

<script setup>
    import {nextTick, reactive, ref, onMounted,computed} from 'vue'
    import ClientLogin from "@/views/client/ClientLogin.vue"
    import {ElMessage} from 'element-plus'
    import request from '@/utils/request.js'
    import moment from 'moment'
    let customer = reactive({nickName:"XX"})
    let clientLogin = ref(null)
    let msgArea = ref()
    let chatId;
    let userId  = new Date().getTime().toString();
    let websocket =  null

    onMounted(()=>{
        document.querySelector("title").text = "客服系统客户端"
        // request.get(`/api/client/getChatId/${userId}`).then(resp => {
            clientLogin.value.showDialog = true
        // });
    })

    function logined(cust) {
        for(let key in cust){
            customer[key] = cust[key]
        }
        websocket  = new WebSocket("ws://localhost:9080/online/client/"+customer.id)

        websocket.onopen = function(){
            getChatId(userId)
        }

        websocket.onerror = function (e) {
            ElMessage({message: "websocket连接出错", type: 'error'})
        }

        websocket.onmessage = function (msg) {
            chat.msgs.push(JSON.parse(msg.data))
            scrollerToBottom()
        }

    }

    let nickName = computed(() => {
        let nickName = customer.nickName
        let len =  nickName.length
        return nickName.substr(len -2, len)
    })

    let chat = reactive(
        {
            alive:true,
            msgs:[
                {"sender":'agent','content':`您好，欢迎使用尤八哥客服系统，我是客服代表，工号111111。很高兴为您服务`,"type":"text","createTime":new Date()},
                ]
        })

    function getChatId(userId){
        request.get(`/api/client/getChatId/${userId}`).then(resp => {
            chatId = resp;
        });
    }

    function send(chat){
        let content = chat.inputBox.trim()
        if(content === ""){
            ElMessage({message: "请输入内容",type: 'error'})
            return
        }
        let time = moment().format("yyyy-MM-DD HH:mm:ss")
        let msg = {"sender":'client',"content": content,"type": "text", "chatId":chatId, "clientName":customer.nickName, "clientId":customer.id}
        if(WebSocket.OPEN === websocket.readyState){
            websocket.send(JSON.stringify(msg))
            // chat.msgs.push(msg)
            chat.inputBox = ""
            scrollerToBottom(chat.clientName)
        }else{
            ElMessage({message: "会话已经断开",type: 'error'})
            chat.alive = false
        }
    }

    function scrollerToBottom() {
        nextTick(function () {
            msgArea.value.scrollTop = msgArea.value.scrollHeight
        })
    }

</script>
<style lang="css">
    .tip {
        border-radius: 10px;
        padding: 10px;
        width:auto;
        display:inline-block !important;
        word-wrap: break-word;
        word-break: break-all;
        text-align:left;
        max-width:60%;
    }
    .time {
        padding: 5px;
        display:inline-block;
        color: #9a9b9e;
        font-size: 13px;
    }
    .item {
        margin-top: 5px;
    }
    .right {
        background-color:  #a7e861;
    }
    .left {
        background-color:  white;
    }
    .span-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;}
    .btn-bell-badge {
        width: 26px;
        height: 18px;
        margin-left:5px;
        line-height:18px;
        border-radius: 15px;
        background: #f56c6c;}
    .num {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #fff;
    }

</style>